package com.web.controller.load;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import com.web.common.domain.AjaxResult;
import com.web.common.page.TableDataInfo;
import com.web.controller.common.BaseController;
import com.web.entity.SysFile;
import com.web.service.SysFileService;
import com.web.utils.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;


/**
 * 系统文件记录Controller
 *
 * @author liuyanlong
 * @date 2021-12-05
 */
@Controller
@RequestMapping("/load")
public class SysFileController extends BaseController{
    private String prefix = "load";
    //服务器本地路径 liunx
    // private static final String filePath = "/load/";
    //服务器本地路径 windows todo 后期可以配置到 yml 文件中
    private static final String filePath = "D:/load/";


    @Autowired
    private SysFileService sysFileService;


    @GetMapping()
    public String file() {
        return prefix + "/load";
    }

    /**
     * @Author liuyanlong
     * @Description 文件上传
     * @Description REST风格 -POST(上传文件)
     * @Date 2021/12/5  下午 1:28
     **/
    @RequestMapping(value = "/load", method = RequestMethod.POST)
    public String upLoad(@RequestParam(value = "files") MultipartFile files) throws IOException {
        String fileName = null;
        if (!files.isEmpty()) {
            try {
                fileName = files.getOriginalFilename();
                //文件编码--防止文件在liunx 服务器运行 中文 出现乱码
                final String fileId = UuidUtil.uuid32();
                //上传到服务器的路径
                String path = filePath + fileId;
                //上传到服务器上
                byte[] bytes = files.getBytes();
                BufferedOutputStream buffStream =
                        new BufferedOutputStream(new FileOutputStream(new File(path)));
                buffStream.write(bytes);
                buffStream.flush();
                buffStream.close();
                //将文件信息保存到数据中
                SysFile sysFile = new SysFile(fileId, fileName, path);
                sysFileService.insertSysFile(sysFile);
                return "redirect:";
            } catch (Exception e) {
                return "You failed to upload " + fileName + ": " + e.getMessage();
            }
        } else {
            return "Unable to upload. File is empty.";
        }
    }

    /**
     * @Author liuyanlong
     * @Description 文件 下载
     * @Date 2021/12/5  下午 1:28
     **/

    @GetMapping("download")
    public void downloadFile(HttpServletResponse response, @RequestParam("fileId") String fileId) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        //通过文件编码 fileId 从数据库获取到文件信息
        final SysFile sysFile = sysFileService.selectSysFileById(fileId);
        if (sysFile == null) {
            response.getWriter().print(
                    "<script language=javascript>alert('该文件已被删除！');" +
                            "window.location.href='" + prefix + "/load" + "';</script>");
            return;
        }
        //下载时防止中文下载过程中出现乱码使用编码进行替代
        final String fileName = sysFile.getFileName();
        final int i = fileName.indexOf(".");
        String suffix = "";
        if (i > 0) {
            suffix = fileName.substring(i);
        }
        //下载时防止中文下载过程中出现乱码使用编码进行替代 windows 环境也可以用过 fileName 这里用 fileId
        response.setHeader("Content-Disposition", "attachment;fileName=" + sysFile.getFileId() + suffix);
        try {
            String path = sysFile.getFilePath();
            File files = new File(path);
            System.out.println(files.getAbsolutePath());
            InputStream inputStream = new FileInputStream(path);
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[1024];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询系统文件记录列表
     * @Description REST风格 -GET(获取文件记录列表)
     */
    @RequestMapping(value = "/load", method = RequestMethod.GET)
    @ResponseBody
    public TableDataInfo list(SysFile sysFile) throws Exception {
        startPage();
        List<SysFile> list = sysFileService.selectSysFileList(sysFile);
        return getDataTable(list);
    }


    /**
     * @Description REST风格 -DELETE(上传文件)
     * 删除系统文件记录 并删除 服务器上的文件
     */

    @RequestMapping(value = "/load", method = RequestMethod.DELETE)
    @ResponseBody
    public AjaxResult remove(String ids) {
        //获取文件信息
        final SysFile sysFile = sysFileService.selectSysFileById(ids);
        //获取文件在服务器上的路径
        String path = sysFile.getFilePath();
        File files = new File(path);
        System.out.println(files.getAbsolutePath());
        //删除服务器文件
        files.delete();
        //删除数据库记录
        final int del = sysFileService.deleteSysFileByIds(ids);
        return toAjax(del);
    }
}
